package com.keyinong.caizhengting.fragment;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.keyinong.caizhengting.R;
import com.keyinong.caizhengting.activity.GoodsDetailActivity;
import com.keyinong.caizhengting.adapter.GoodsAdapter;
import com.keyinong.caizhengting.adapter.ShouyetuijianAdapter;
import com.keyinong.caizhengting.entity.ShangpinEntity;
import com.keyinong.caizhengting.tools.HttpTools;
import com.keyinong.caizhengting.tools.NetWorkUtil;
import com.loopj.android.http.JsonHttpResponseHandler;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * 商品二级分类
 */
public class GoodsTwoSortFragment extends Fragment {
    HttpTools toolModel = null;
    //	String catid;
    String varid;
    String token;
    int width;
    int height;

    private int mType;
    /**
     * 上下拉刷新
     */
    private PullToRefreshListView pull_twosort;
    /**
     * 商品信息的集合
     */
    private List<ShangpinEntity> goodslist;
    private int offset = 0;
    private int page = 10;
    /**
     * 没有商品
     */
    private TextView tv_none;
    private String id;
    private ShouyetuijianAdapter adapter;

    private GoodsAdapter mGoodsAdapter;

    private int mGoodsNum;
    /**
     * 上下拉刷新
     */
    private OnRefreshListener2<ListView> onrefresh = new OnRefreshListener2<ListView>() {

        @Override
        public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
            offset = 0;
            goodslist.clear();
            toolModel.getTwoSort(token, varid, page + "", offset + "", new JsonGetGoodsInfo());
            if (!NetWorkUtil.isNetwork(getActivity())) {
                Toast.makeText(getActivity(), "当前网络不可用", Toast.LENGTH_SHORT).show();
                pull_twosort.onRefreshComplete();
                return;
            }

        }

        @Override
        public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
            offset += page;
            toolModel.getTwoSort(token, varid, page + "", offset + "", new JsonGetGoodsInfo());
            if (!NetWorkUtil.isNetwork(getActivity())) {
                Toast.makeText(getActivity(), "当前网络不可用", Toast.LENGTH_SHORT).show();
                pull_twosort.onRefreshComplete();
                return;
            }
        }

    };

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.iten_fragmen_twosort, null);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initRes();
    }

    private void initRes() {
        pull_twosort = (PullToRefreshListView) getView().findViewById(R.id.pull_twosort);

        pull_twosort.setMode(Mode.BOTH);
        pull_twosort.setOnRefreshListener(onrefresh);
//		pull_twosort.setOnItemClickListener(itemclicke);
        tv_none = (TextView) getView().findViewById(R.id.tv_none);

        Bundle bundle = getArguments();
//		catid = bundle.getString("catid");
        varid = bundle.getString("varid");
        mType = bundle.getInt("type");
//		Log.e("info","-----1");
        getGoodsInfo(varid);
        SharedPreferences spwm = getActivity().getSharedPreferences("spWM", Context.MODE_PRIVATE);
        width = spwm.getInt("width", 720);
        height = spwm.getInt("height", 1280);
    }

    /**
     * 获取分类商品
     */
    private void getGoodsInfo(String varid) {
        if (!NetWorkUtil.isNetwork(getActivity())) {
            Toast.makeText(getActivity(), "当前网络不可用", Toast.LENGTH_SHORT).show();
            return;
        }
//		Log.e("info","-----2");
        goodslist = new ArrayList<>();
        SharedPreferences sp = getActivity().getSharedPreferences("spReg",
                Context.MODE_PRIVATE);
        token = sp.getString("data", "");

        toolModel = new HttpTools(getActivity());
        toolModel.getTwoSort(token, varid, page + "", offset + "",
                new JsonGetGoodsInfo());
    }

    private class JsonGetGoodsInfo extends JsonHttpResponseHandler {

        /*
        @Override
        public void onSuccess(int statusCode, Header[] headers,
                              JSONArray response) {
            super.onSuccess(statusCode, headers, response);

            try {
                Log.i("info", "分类加载----" + response.toString());
                for (int i = 0; i < response.length(); i++) {
                    JSONObject data = response.getJSONObject(i);
                    id = data.getString("id");
                    String name = data.getString("name");
                    String content = data.getString("content");
                    String price = data.getString("price");
                    String image = data.getString("image");
                    String unit = data.getString("unit");
                    String stock = data.getString("stock");
                    String perlim = data.getString("perlim");
                    String sellnum = data.getString("sellnum");
                    String amount = data.getString("amount");
                    String buyamount = data.getString("buyamount");

                    goodslist.add(new ShangpinEntity(id, name, image, content, price, amount, unit, stock, perlim, sellnum, buyamount));
                }
                if (goodslist.size() == 0) {
                    tv_none.setVisibility(View.VISIBLE);
                } else {
                    tv_none.setVisibility(View.GONE);
                }
                adapter = new ShouyetuijianAdapter(getActivity(), goodslist);
                pull_twosort.setAdapter(adapter);
                pull_twosort.getRefreshableView().setSelection(offset);
                pull_twosort.setDividerDrawable(null);
//				Utility.setGridViewHeightBasedOnChildren(pull_twosort);
                pull_twosort.onRefreshComplete();
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }*/

        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
            super.onSuccess(statusCode, headers, response);
            Log.w("WZY", response.toString());

            try {
                JSONArray array = response.getJSONArray("data");
                for (int i = 0; i < array.length(); i++) {
                    JSONObject data = array.getJSONObject(i);
                    id = data.getString("id");
                    String name = data.getString("name");
                    String content = data.getString("content");
                    String price = data.getString("price");
                    String image = data.getString("image");
                    String unit = data.getString("unit");
                    String stock = data.getString("stock");
                    String perlim = data.getString("perlim");
                    String daylim = data.getString("daylim");
                    String sellnum = data.getString("sellnum");
                    String amount = data.getString("amount");
                    String buyamount = data.getString("buyamount");

                    goodslist.add(new ShangpinEntity(id, name, image, content, price, amount, unit, stock, perlim, daylim, sellnum, buyamount));
                }
                if (goodslist.size() == 0) {
                    tv_none.setVisibility(View.VISIBLE);
                } else {
                    tv_none.setVisibility(View.GONE);
                }

                if (mType == 0) {
                    adapter = new ShouyetuijianAdapter(getActivity(), goodslist);
                    pull_twosort.setAdapter(adapter);
                } else {
                    mGoodsAdapter = new GoodsAdapter(getActivity(), goodslist);
                    pull_twosort.setAdapter(mGoodsAdapter);
                    pull_twosort.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                            Log.w("TAG", "position" + l + " ----- " + goodslist.get(i - 1).toString());
                            mGoodsNum = mGoodsAdapter.getGoodsNum();
                            //mGoodsNum = view
                            Intent intent = new Intent(GoodsTwoSortFragment.this.getActivity(), GoodsDetailActivity.class);
                            Bundle bundle = new Bundle();
                            bundle.putSerializable("GOODS_DETAIL", goodslist.get(i - 1));
                            bundle.putInt("GOODS_NUM", mGoodsNum);
                            intent.putExtras(bundle);
                            startActivity(intent);
                        }
                    });
                }

                pull_twosort.getRefreshableView().setSelection(offset);
                pull_twosort.setDividerDrawable(null);
                pull_twosort.onRefreshComplete();

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }


}
